<?php
namespace app\index\model;
use think\Session;
use think\Cookie;
use think\Request;
/**
 * 用户模型
 */
class Users extends \think\Model
{
	protected $table = 'users';
	public function login($data){
		if(self::getUserInfo(['account' => $data['account']])){
			$data['password'] = md5($data['password']);
			if($userInfo = self::getUserInfo($data)){
				$this->setUserSession($userInfo);
				//存入微信用户的opendID
				if($userInfo->opend_id != Cookie::get('auth_id')){
					$userInfo->opend_id = Cookie::get('auth_id');
					$userInfo->save();
				}
				return ['code' => 200, 'msg' => '登陆成功'];
			}else{
				return ['code' => 101, 'msg' => '账号或密码错误'];
			}
		}else{
			return ['code' => 100, 'msg' => '该账号不存在'];
		}
	}
	
	public function getUserInfo($where, $field = ''){
		if($userInfo = self::get($where)){
			Request::instance()->bind('userInfo', $userInfo);
			if($field){
				if(isset($userInfo->$field)){
					return $userInfo->$field;
				}
				return false;				
			}
			return $userInfo;
		}
		return false;	    
	}
	
	/**
	 * opendId登录
	 */
	public function loginByOpendId($opend_id){
	    if(!$this->checkLogin()){
	    	if($userInfo = self::getUserInfo(['opend_id' => $opend_id])){
	    		$this->setUserSession($userInfo);
				return true;
	    	}
			return false;
	    }
		return true;
	}
	
	/**
	 * 检测用户是否登录
	 */
	public function checkLogin(){
	    return Session::get('wx_user') ? true : false;
	}
	
	/**
	 * 设置用户session
	 */
	public function setUserSession($userInfo){
		Session::set('wx_user.id', $userInfo->id);
		Session::set('wx_user.account', $userInfo->account);	    
	}
	
	
	/**
	 * 添加会员
	 */
	public function addUser($user_info = [])
    {
    	if (false === $this->checkUser($user_info, ['account'])) {
    		$user_info['password'] = md5($user_info['password']);
    		self::create($user_info, true);
			return ['code' => 200, 'msg' => '注册成功'];
    	}else {
    		return ['code' => 102, 'msg' => '该账号已注册'];
    	}	
    }
    /**
     * 校验用户信息是否存在
     * @param  [type] $user_info [description]
     * @param  array  $onlys     [description]
     * @return [type]            [description]
     */
    public function checkUser($user_info, $onlys = [])
    {
    	$user_info = $onlys ? array_intersect_key($user_info, array_flip($onlys)) : $user_info;
    	if (!empty($user_info)) {
    		foreach ($user_info as $key => $data) {
	    		if (self::getUserInfo([$key => $data])) {
	            	return true;
	        	}
	    	}
    	}   	
    	return false;
    }
	
}
 
 
 
 

 
 
 
 
?>